<?php

class Image {
	
	/**
	 * @var string
	 */
	private $name;
	private $extension;
	private $tempName;
	
	/**
	 * @param string $extension
	 * @param string $tempName
	 */
	public function __construct($extension, $tempName) {
		$this->setExtension($extension);
		$this->tempName = $tempName;
		
		$this->name = $this->setNewName($this->extension);
	}
	
	public function saveImageOnServer() {
		move_uploaded_file($this->tempName, "./images/$this->name");
	}

	/**
	 * @param string $str
	 */
	public static function deleteOldImage($str) {
		unlink("./images/$str");
	}
	
	/**
	 * @param string $ext
	 * @return string
	 */
	private function setNewName($ext) {
		$str = sha1(time());
		$str = substr($str, rand(6,10), strlen($str));
		return $str.".".$ext;
	}
	
	/**
	 * @param string $ext
	 */
	public function setExtension($ext) {
		switch ($ext) {
			case 'jpg':
				$this->extension = $ext;
				break;
			case 'png':
				$this->extension = $ext;
				break;
			case 'jpeg':
				$this->extension = $ext;
				break;
			case 'gif':
				$this->extension = $ext;
				break;
			default:
				throw new \Exception("Uploaded file must be of type jpg/png/jpeg/gif.");
		}
	}
	
	/**
	 * @return string
	 */
	public function getNewName() {
		return $this->name;
	}
	
	/**
	 * @return string
	 */
	public function getTempName() {
		return $this->tempName;
	}
}